package com.lsl.endworkvol.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lsl.endworkvol.dao.LeaderMapper;
import com.lsl.endworkvol.entity.Activity;
import com.lsl.endworkvol.entity.Leader;
import com.lsl.endworkvol.service.ActivityService;
import com.lsl.endworkvol.service.LeaderService;
import com.lsl.endworkvol.service.func.IUserBuilder;

@Service
public class LeaderServiceImpl implements LeaderService{

    @Autowired
    private LeaderMapper leaderMapper;

    @Autowired
    private ActivityService activityService;

    @Override
    public boolean addUser(IUserBuilder builder) {
        return leaderMapper.insertLeader((Leader)builder.build()) > 0;
    }

    @Override
    public boolean editUser(IUserBuilder builder) {
        Leader leader = (Leader)builder.build();
        if (leader.getUsername() == null) {    // 用户名为null：代表用户正在被重置信息
            Leader temp = getUser(leader.getId());
            leader.setUsername(temp.getUsername());
            leader.setPassword(temp.getPassword());
        }
        if (leader.getPassword().isEmpty()) {   // 密码为空：代表用户不修改密码
            leader.setPassword(getUser(leader.getId()).getPassword());
        }
        return leaderMapper.updateLeader(leader) > 0;
    }

    @Override
    public Leader getUser(Integer id) {
        return leaderMapper.selectLeaderById(id);
    }

    @Override
    public boolean deleteUser(Integer id) {
        List<Activity> activities = activityService.getActivities(String.valueOf(id));
        for (Activity activity : activities) {
            if (!activityService.deleteActivity(String.valueOf(activity.getId()))){
                return false;
            }
        }
        return leaderMapper.deleteLeader(id) > 0;
    }

    @Override
    public boolean loginCheck(String id, String password) {
        Leader Leader = (Leader) getUser(Integer.parseInt(id));
        return Leader != null && Leader.getPassword().equals(password);
    }

    @Override
    public List<Leader> getUsers(IUserBuilder builder) {
        return leaderMapper.blurLeaders((Leader)builder.build());
    }

    @Override
    public List<Leader> getUsers() {
        return leaderMapper.selectAllLeader();
    }

}
